package com.dwusoft.sendmsg.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
/**
 * 
 * @author guogf
 *
 */
public class Md5Tools {

	private static final char hexDigits[] = { '0', '1', '2', '3', '4', '5',
			'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	private static String byteToString(byte abyte0[]) {
		int i = abyte0.length;
		char ac[] = new char[i * 2];
		int j = 0;
		for (int k = 0; k < i; k++) {
			byte byte0 = abyte0[k];
			ac[j++] = hexDigits[byte0 >>> 4 & 0xf];
			ac[j++] = hexDigits[byte0 & 0xf];
		}
		return new String(ac);
	}

	/**
	 * @fun Get Md5 value of String
	 * @param s
	 * @return
	 * @throws Exception
	 */
	public static String getMd5(String s) throws Exception {
		MessageDigest messagedigest = MessageDigest.getInstance("MD5");
		messagedigest.reset();
		byte abyte0[] = messagedigest.digest(s.getBytes());
		return byteToString(abyte0);
	}
	 public static byte[] getByte(File file){
			byte[] bytes = null;
			if (file != null) {
				InputStream is = null;
				try {
					is = new FileInputStream(file);
					int length = (int) file.length();
					if (length > Integer.MAX_VALUE)
					{
					//	LogUtil.logDebug("this file is max ");
						return null;
					}
					bytes = new byte[length];
					int offset = 0;
					int numRead = 0;
					while (offset < bytes.length
							&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
						offset += numRead;
					}
					if (offset < bytes.length) {
					//	LogUtil.logDebug("file length is error");
						return null;
					}
				} catch (FileNotFoundException e) {
				//	LogUtil.log(e);
				} catch (IOException e) {
				//	LogUtil.log(e);
				} finally {
					try {
						if(is != null) {
							is.close();
						}
					} catch (IOException e) {
				//		LogUtil.log(e);
					}
				}
			}
			return bytes;
		}
}
